<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="800px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="right"
    >
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="数据源名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入数据源名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据源类型">
                <el-input :value="'MQTT'" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入数据源描述"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>

        <!-- 连接配置 -->
        <el-tab-pane label="连接配置" name="connection">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="服务器地址" prop="connectionConfig.host">
                <el-input v-model="formData.connectionConfig.host" placeholder="请输入MQTT服务器地址" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="端口" prop="connectionConfig.port">
                <el-input-number
                  v-model="formData.connectionConfig.port"
                  :min="1"
                  :max="65535"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="客户端ID" prop="connectionConfig.clientId">
            <el-input v-model="formData.connectionConfig.clientId" placeholder="请输入客户端ID" />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="connectionConfig.username">
                <el-input v-model="formData.connectionConfig.username" placeholder="请输入用户名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码" prop="connectionConfig.password">
                <el-input
                  v-model="formData.connectionConfig.password"
                  type="password"
                  placeholder="请输入密码"
                  show-password
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="主题订阅" prop="connectionConfig.topics">
            <el-button
              type="primary"
              size="small"
              @click="addTopic"
              style="margin-bottom: 10px"
            >
              添加订阅主题
            </el-button>
            <el-table
              :data="formData.connectionConfig.topics"
              border
              style="width: 100%"
              empty-text="暂无主题配置"
            >
              <el-table-column prop="topic" label="主题" width="300">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.topic"
                    placeholder="例如: sensor/data/#"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="qos" label="QoS" width="120">
                <template #default="{ row, $index }">
                  <el-select v-model="row.qos" placeholder="选择QoS">
                    <el-option label="0" :value="0" />
                    <el-option label="1" :value="1" />
                    <el-option label="2" :value="2" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeTopic($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item label="SSL/TLS" prop="connectionConfig.ssl">
            <el-switch v-model="formData.connectionConfig.ssl" />
          </el-form-item>

          <template v-if="formData.connectionConfig.ssl">
            <el-form-item label="CA证书" prop="connectionConfig.ca">
              <el-input
                v-model="formData.connectionConfig.ca"
                type="textarea"
                :rows="3"
                placeholder="请输入CA证书内容"
              />
            </el-form-item>
            <el-form-item label="客户端证书" prop="connectionConfig.cert">
              <el-input
                v-model="formData.connectionConfig.cert"
                type="textarea"
                :rows="3"
                placeholder="请输入客户端证书内容"
              />
            </el-form-item>
            <el-form-item label="客户端密钥" prop="connectionConfig.key">
              <el-input
                v-model="formData.connectionConfig.key"
                type="textarea"
                :rows="3"
                placeholder="请输入客户端密钥内容"
              />
            </el-form-item>
          </template>

          <el-form-item label="保持连接" prop="connectionConfig.keepalive">
            <el-input-number
              v-model="formData.connectionConfig.keepalive"
              :min="5"
              :max="600"
              controls-position="right"
              style="width: 100%"
            />
            <span class="el-form-item__tip">(秒，默认60秒)</span>
          </el-form-item>

          <el-form-item label="自动重连" prop="connectionConfig.reconnect">
            <el-switch v-model="formData.connectionConfig.reconnect" />
          </el-form-item>
        </el-tab-pane>

        <!-- 数据格式配置 -->
        <el-tab-pane label="数据格式" name="dataFormat">
          <el-form-item label="消息格式" prop="dataFormatConfig.format">
            <el-select
              v-model="formData.dataFormatConfig.format"
              placeholder="请选择消息格式"
              style="width: 100%"
            >
              <el-option label="JSON" value="JSON" />
              <el-option label="XML" value="XML" />
              <el-option label="Text" value="TEXT" />
              <el-option label="Binary" value="BINARY" />
            </el-select>
          </el-form-item>

          <el-form-item label="编码格式" prop="dataFormatConfig.encoding">
            <el-select
              v-model="formData.dataFormatConfig.encoding"
              placeholder="请选择编码格式"
              style="width: 100%"
            >
              <el-option label="UTF-8" value="UTF-8" />
              <el-option label="GBK" value="GBK" />
              <el-option label="ISO-8859-1" value="ISO-8859-1" />
            </el-select>
          </el-form-item>

          <el-form-item label="时间戳字段" prop="dataFormatConfig.timestampField">
            <el-input
              v-model="formData.dataFormatConfig.timestampField"
              placeholder="例如: timestamp (留空表示不使用)"
            />
          </el-form-item>

          <el-form-item label="消息解析脚本" prop="dataFormatConfig.script">
            <el-input
              v-model="formData.dataFormatConfig.script"
              type="textarea"
              :rows="5"
              placeholder="可输入自定义解析脚本(JavaScript)"
            />
            <span class="el-form-item__tip">可选，用于自定义消息解析逻辑</span>
          </el-form-item>
        </el-tab-pane>

        <!-- 高级配置 -->
        <el-tab-pane label="高级配置" name="advanced">
          <el-form-item label="缓存配置" prop="cacheConfig.enabled">
            <el-switch
              v-model="formData.cacheConfig.enabled"
              active-text="启用缓存"
              inactive-text="禁用缓存"
            />
          </el-form-item>
          <el-form-item
            v-if="formData.cacheConfig.enabled"
            label="缓存时间(秒)"
            prop="cacheConfig.ttl"
          >
            <el-input-number
              v-model="formData.cacheConfig.ttl"
              :min="60"
              :max="86400"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="消息过滤" prop="filterConfig.enabled">
            <el-switch
              v-model="formData.filterConfig.enabled"
              active-text="启用过滤"
              inactive-text="禁用过滤"
            />
          </el-form-item>
          <template v-if="formData.filterConfig.enabled">
            <el-form-item label="过滤条件" prop="filterConfig.condition">
              <el-input
                v-model="formData.filterConfig.condition"
                type="textarea"
                :rows="3"
                placeholder="输入JavaScript条件表达式，例如: payload.temperature > 30"
              />
            </el-form-item>
          </template>

          <el-form-item label="消息转换" prop="transformConfig.enabled">
            <el-switch
              v-model="formData.transformConfig.enabled"
              active-text="启用转换"
              inactive-text="禁用转换"
            />
          </el-form-item>
          <template v-if="formData.transformConfig.enabled">
            <el-form-item label="转换脚本" prop="transformConfig.script">
              <el-input
                v-model="formData.transformConfig.script"
                type="textarea"
                :rows="5"
                placeholder="输入JavaScript转换脚本，例如: return { ...payload, processed: true }"
              />
            </el-form-item>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'EditMqttDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'submit'],
  setup(props, { emit }) {
    const visible = computed({
      get: () => props.modelValue,
      set: (val) => emit('update:modelValue', val)
    })

    const title = computed(() => 
      props.editData ? '编辑MQTT数据源' : '新增MQTT数据源'
    )

    const activeTab = ref('basic')
    const formRef = ref(null)

    // 默认表单数据
    const defaultFormData = {
      id: '',
      name: '',
      description: '',
      status: 1,
      connectionConfig: {
        host: '',
        port: 1883,
        clientId: `mqtt_${Math.random().toString(16).substr(2, 8)}`,
        username: '',
        password: '',
        topics: [],
        ssl: false,
        ca: '',
        cert: '',
        key: '',
        keepalive: 60,
        reconnect: true,
        cleanSession: true,
        protocolVersion: 4 // MQTT v3.1.1
      },
      dataFormatConfig: {
        format: 'JSON',
        encoding: 'UTF-8',
        timestampField: '',
        script: ''
      },
      cacheConfig: {
        enabled: true,
        ttl: 3600
      },
      filterConfig: {
        enabled: false,
        condition: ''
      },
      transformConfig: {
        enabled: false,
        script: ''
      }
    }

    const formData = ref(JSON.parse(JSON.stringify(defaultFormData)))

    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: '请输入数据源名称', trigger: 'blur' },
        { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
      ],
      'connectionConfig.host': [
        { required: true, message: '请输入服务器地址', trigger: 'blur' }
      ],
      'connectionConfig.port': [
        { required: true, message: '请输入端口号', trigger: 'blur' }
      ],
      'connectionConfig.clientId': [
        { required: true, message: '请输入客户端ID', trigger: 'blur' }
      ],
      'connectionConfig.topics': [
        { 
          validator: (rule, value, callback) => {
            if (!value || value.length === 0) {
              return callback(new Error('至少需要配置一个订阅主题'))
            }
            const hasEmpty = value.some(item => !item.topic)
            if (hasEmpty) {
              callback(new Error('主题不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        }
      ],
      'dataFormatConfig.format': [
        { required: true, message: '请选择消息格式', trigger: 'change' }
      ],
      'cacheConfig.ttl': [
        { required: true, message: '请输入缓存时间', trigger: 'blur' }
      ]
    }

    // 添加主题
    const addTopic = () => {
      formData.value.connectionConfig.topics.push({
        topic: '',
        qos: 0
      })
    }

    // 删除主题
    const removeTopic = (index) => {
      formData.value.connectionConfig.topics.splice(index, 1)
      validateTopics()
    }

    // 验证主题
    const validateTopics = () => {
      formRef.value.validateField('connectionConfig.topics')
    }

    // 对话框关闭
    const handleClosed = () => {
      formRef.value?.resetFields()
      formData.value = JSON.parse(JSON.stringify(defaultFormData))
    }

    // 提交表单
    const submitForm = async () => {
      try {
        await formRef.value.validate()
        
        // 处理主题，过滤空值
        const finalData = JSON.parse(JSON.stringify(formData.value))
        finalData.connectionConfig.topics = finalData.connectionConfig.topics
          .filter(item => item.topic)
        
        // 如果不使用SSL，清空相关字段
        if (!finalData.connectionConfig.ssl) {
          finalData.connectionConfig.ca = ''
          finalData.connectionConfig.cert = ''
          finalData.connectionConfig.key = ''
        }
        
        emit('submit', finalData)
        visible.value = false
      } catch (error) {
        console.error('表单验证失败:', error)
        ElMessage.error('请检查表单填写是否正确')
      }
    }

    // 监听编辑数据变化
    watch(() => props.editData, (newVal) => {
      if (newVal) {
        formData.value = JSON.parse(JSON.stringify({
          ...defaultFormData,
          ...newVal,
          connectionConfig: {
            ...defaultFormData.connectionConfig,
            ...(newVal.connectionConfig || {})
          },
          dataFormatConfig: {
            ...defaultFormData.dataFormatConfig,
            ...(newVal.dataFormatConfig || {})
          },
          cacheConfig: {
            ...defaultFormData.cacheConfig,
            ...(newVal.cacheConfig || {})
          },
          filterConfig: {
            ...defaultFormData.filterConfig,
            ...(newVal.filterConfig || {})
          },
          transformConfig: {
            ...defaultFormData.transformConfig,
            ...(newVal.transformConfig || {})
          }
        }))
        
        // 确保topics是数组
        if (!Array.isArray(formData.value.connectionConfig.topics)) {
          formData.value.connectionConfig.topics = []
        }
      }
    }, { immediate: true })

    return {
      visible,
      title,
      activeTab,
      formRef,
      formData,
      formRules,
      addTopic,
      removeTopic,
      validateTopics,
      handleClosed,
      submitForm
    }
  }
}
</script>

<style scoped>
.el-form-item__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  display: inline-block;
}
</style>